/*
 * Copyright (c) 2011 Auzingers
 * Created by Oui-IT
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.auzingers.docsorganizer.gui;

import com.auzingers.docsorganizer.service.DocsOrganizerDbService;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;

/**
 * Base class for activities that need access to the database.
 */
public abstract class AbstractDbActivity extends AbstractActivity {

    private DocsOrganizerDbService dbService = null;

    private boolean mIsBound = false;

    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            dbService = ((DocsOrganizerDbService.LocalBinder) service).getService();
            dbServiceConnected();
        }

        public void onServiceDisconnected(ComponentName className) {
            dbService = null;
        }
    };

    /**
     * Callback method when the database service has connected.
     */
    void dbServiceConnected() {
        //can be overwritten in subclass
    }

    /**
     * Binds the db service.
     */
    private void doBindService() {
        bindService(new Intent(this, DocsOrganizerDbService.class), mConnection, Context.BIND_AUTO_CREATE);
        mIsBound = true;
    }

    /**
     * Unbinds the db service.
     */
    void doUnbindService() {
        if (mIsBound) {
            // Detach our existing connection.
            unbindService(mConnection);
            mIsBound = false;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        doBindService();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        doUnbindService();
    }

    protected DocsOrganizerDbService getDb() {
        return dbService;
    }
}
